﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using AgileDashboard.Entities;
using AgileDashboard.Data;
using PlanningPokerMVC.Helpers;
using Newtonsoft.Json;

namespace PlanningPokerMVC.Controllers
{
    public class HomeController : Controller
    {

        private PlanningPokerContext db = new PlanningPokerContext();

        public ActionResult Index()
        {

            using (var db = new PlanningPokerContext())
            {
                foreach (WorkItem wi in db.WorkItems)
                {
                    //wi.CanVote 
                    var voteCount = (from v in wi.VoteDetails
                                select v).Count();

                    wi.VoteCount = voteCount;


                    var userVotes = (from v in wi.VoteDetails
                                     where v.UserName == User.Identity.Name
                                     select v).Count();

                    if (userVotes == 0)
                        wi.CanVote = true;


                }

                return View(db.WorkItems.ToList());
            }

        }

        public ActionResult Edit(int Id)
        {
            var workItem = (from w in db.WorkItems
                            where w.Id == Id
                            select w).FirstOrDefault();

            return View(workItem);

        }







        [HttpPost]
        public ActionResult Edit(WorkItem workItem)
        {

            if (ModelState.IsValid)
            {
                WorkItem wi = db.WorkItems.Find(workItem.Id);


                wi.UpdatedBy = User.Identity.Name;
                wi.UpdateTimeStamp = DateTime.Now;
                wi.WinningVote = workItem.WinningVote;
                wi.Status = workItem.Status;

                db.SaveChanges();
                return RedirectToAction("Index","PlanningPoker");
            }
            return View(workItem);

        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(WorkItem workItem)
        {
            try
            {
                using (var db = new PlanningPokerContext())
                {



                    db.WorkItems.Add(workItem);
                    db.SaveChanges();
                }
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
